package com.gepengjun.lims.config.shiro.filter;

import com.alibaba.fastjson.JSON;
import com.gepengjun.lims.util.JsonResult.ResultUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.web.filter.authz.RolesAuthorizationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class ShiroRolesFilter extends RolesAuthorizationFilter {
    @Override
    protected boolean onAccessDenied(ServletRequest req, ServletResponse res) throws IOException {
        System.out.println("ShiroRolesFilter--onAccessDenied-");
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        String requestedWith = request.getHeader("X-Requested-With");
        if (StringUtils.isNotEmpty(requestedWith) && StringUtils.equals("XMLHttpRequest",requestedWith)){
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            response.getWriter().write(JSON.toJSONString(ResultUtil.error(403,"无权限-无指定角色 ")));
        }else {
            response.sendRedirect("/unautho");
        }
        return false;
    }
}
